package com.wkh.project.factory.defaults;

import com.wkh.project.factory.Configuration;
import com.wkh.project.factory.PayFactory;
import com.wkh.project.payment.h5pay.H5PayService;
import com.wkh.project.payment.h5pay.IH5PayApi;
import com.wkh.project.payment.navivepay.INativePayApi;
import com.wkh.project.payment.navivepay.NativePayService;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author wangkehua
 * pay工厂类实现
 */
public class DefaultPayFactory implements PayFactory {

    private final Configuration configuration;
    private final OkHttpClient okHttpClient;
    public DefaultPayFactory(Configuration configuration) {
        this.configuration = configuration;
        //日志配置
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(configuration.getLogLevel());
        //开启HTTP客户端
        this.okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(configuration.getConnectTimeout(), TimeUnit.SECONDS)
                .writeTimeout(configuration.getWriteTimeout(), TimeUnit.SECONDS)
                .readTimeout(configuration.getReadTimeout(), TimeUnit.SECONDS)
                .build();
    }

    @Override
    public NativePayService nativePayService() {
        //构建API
        INativePayApi nativePayApi = new Retrofit.Builder()
                .baseUrl(configuration.getApiHost())
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build()
                .create(INativePayApi.class);
        //返回服务
        return new NativePayService(nativePayApi,configuration);
    }

    @Override
    public H5PayService h5PayService() {
        //构建API
        IH5PayApi h5PayApi = new Retrofit.Builder()
                .baseUrl(configuration.getApiHost())
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build()
                .create(IH5PayApi.class);
        //返回服务
        return new H5PayService(h5PayApi,configuration);
    }
}
